<template>
  <div class="building">
    <a-card>
      <template #title>
        <a-form layout="inline" :model="formState" @finish="onSearch">
          <a-form-item :style="{ width: '18.75rem' }">
            <a-input v-model:value="formState.search" placeholder="输入宿舍楼名称">
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" shape="circle" html-type="submit">
              <template #icon><SearchOutlined /></template>
            </a-button>
            <a-button shape="circle" style="margin-left: 8rpx" @click="onRest">
              <template #icon><CloseCircleOutlined /></template>
            </a-button>
          </a-form-item>
        </a-form>
      </template>
      <template #extra>
        <a-button type="primary" @click="onEdit('add')">添加</a-button>
      </template>
      <a-table
        row-key="id"
        :columns="dataColumns"
        :loading="loading"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        @change="onChange"
      >
      <!-- <template #administrators="{ text }">
          <p>{{text}}</p>
        </template> -->
        <template #operation="{ record }">
          <div class="operation-box">
            <a-button type="primary" @click="onEdit('update', record)"
              >修改</a-button
            >
            <a-button @click="onEdit('del', record)">删除</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="visible"
      :title="title"
      :destroyOnClose="true"
      :footer="null"
    >
      <template v-if="option !== 'del'">
        <a-form
          ref="buildingFormRef"
          :rules="buildingRules"
          :model="buildingForm"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item v-show="false" label="id" ref="id" name="id">
            <a-input v-model:value="buildingForm.id" />
          </a-form-item>
          <a-form-item label="宿舍楼名称" ref="name" name="name">
            <a-input v-model:value="buildingForm.name" />
          </a-form-item>
          <a-form-item label="可住人数" ref="personNum" name="personNum">
            <a-input v-model:value="buildingForm.personNum" />
          </a-form-item>

          <a-form-item label="所属类别" ref="type" name="type">
            <a-radio-group v-model:value="buildingForm.type">
              <a-radio value="男生宿舍">男生宿舍</a-radio>
              <a-radio value="女生宿舍">女生宿舍</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit">提交</a-button>
          </a-form-item>
        </a-form>
      </template>
      <template v-else>
        <div class="del-modal" style="text-align: center">
          <p>是否删除{{ name }}宿舍楼？</p>
          <a-button type="primary" @click="onDel">删除</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, UnwrapRef } from 'vue'
import { TableState } from 'ant-design-vue/es/table/interface'
import { buildingList, updateBuilding, addBuilding, delBuilding } from '@/api'
import { message } from 'ant-design-vue'
import { useStore } from 'vuex'
type Pagination = TableState['pagination'];
interface FormState {
  search: string | null;
}
interface IbuildingForm {
  id: string | undefined;
  personNum:string;
  type: string;
  name: string;
  modified: string;
  created: string;
  administrators: [];
}

const dataColumns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '宿舍楼名称',
    dataIndex: 'name'
  },
  {
    title: '宿舍楼类别',
    dataIndex: 'type'
  },
  {
    title: '宿舍管理员',
    dataIndex: 'administrators',
    customRender: (e: any) => {
      const { text } = e
      let name = ''

      text.forEach((item:any) => {
        if (item?.name) {
          name += item?.name + '、'
        }
      })

      return name ?? '--'
    }
  },
  {
    title: '可住人数',
    dataIndex: 'person_num',
    customRender: (e: any) => {
      const { text } = e
      return text + '人' ?? '--'
    }
  },
  {
    title: '创建时间',
    dataIndex: 'created'
  },
  {
    title: '修改时间',
    dataIndex: 'modified'
  },

  {
    title: '操作',
    width: '240px',
    dataIndex: 'operation',
    slots: { customRender: 'operation' }
  }
]

export default defineComponent({
  setup () {
    const store = useStore()
    const buildingFormRef = ref()
    const labelCol = store.state.labelCol
    const wrapperCol = store.state.wrapperCol
    const buildingForm: UnwrapRef<IbuildingForm> = reactive({
      id: '',
      type: '',
      name: '',
      personNum: '',
      modified: '',
      created: '',
      administrators: []
    })
    const buildingRules = {
      name: [{ required: true, message: '请输入宿舍楼名称', trigger: 'blur', whitespace: true }],
      type: [{ required: true, message: '请选择宿舍类别', trigger: 'blur', whitespace: true }],
      personNum: [{ required: true, message: '请输入人数', trigger: 'blur', whitespace: true }]
    }

    const formState: UnwrapRef<FormState> = reactive({
      search: ''
    })
    const dataSource = ref([])
    const loading = ref(false)
    const loadingBtn = ref(false)
    // 分页
    const pagination: Pagination = reactive({
      total: 0,
      current: 1,
      pageSize: 5,
      showSizeChanger: true
    })
    const buildingListFunc = async () => {
      loading.value = true
      const {
        data: { data, total }
      } = await buildingList({
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
        keywords: formState.search
      })
      pagination.total = total
      dataSource.value = data
      loading.value = false
    }
    buildingListFunc()
    const onSearch = () => {
      loading.value = true
      updateListFunc(1)
    }
    const onRest = () => {
      loading.value = true
      formState.search = ''
      updateListFunc(1)
    }
    const onChange = (pag: Pagination) => {
      // filters:TableStateFilters, sorter:any, data:any
      loading.value = true
      pagination.pageSize = pag?.pageSize
      updateListFunc(pag?.current)
    }
    // 模态框
    const onSubmit = () => {
      buildingFormRef.value.validate().then(() => {
        if (option.value === 'update') {
          updateBuilding({
            id: buildingForm.id,
            type: buildingForm.type,
            name: buildingForm.name,
            person_num: buildingForm.personNum + ''
          }).then((res) => {
            const {
              data: { status, msg }
            } = res
            if (status === 200) {
              message.success(msg)
            }
          })
        } else {
          addBuilding({
            type: buildingForm.type,
            name: buildingForm.name,
            person_num: buildingForm.personNum
          }).then((res) => {
            const {
              data: { status, msg }
            } = res
            if (status === 200) {
              message.success(msg)
            }
          })
        }
        visible.value = false
        buildingForm.id = ''
        buildingForm.type = ''
        buildingForm.name = ''
        buildingForm.personNum = ''
        loading.value = true
        updateListFunc(1)
      })
    }
    const visible = ref(false)
    const option = ref('')
    const title = ref('')
    const name = ref('')
    const id = ref('')
    const onEdit = async (options: string, obj: any) => {
      id.value = obj?.id ?? ''
      visible.value = true
      if (options === 'add') {
        title.value = '添加宿舍'
        option.value = 'add'
      } else if (options === 'update') {
        title.value = '修改信息'
        buildingForm.id = obj.id
        buildingForm.type = obj.type
        buildingForm.name = obj.name
        buildingForm.personNum = obj.person_num + ''
        option.value = 'update'
      } else if (options === 'del') {
        title.value = '删除管理员'
        name.value = obj.name
        option.value = 'del'
      }
    }
    const onDel = () => {
      delBuilding(id.value).then((res) => {
        const {
          data: { status, msg }
        } = res
        if (status === 200) {
          message.error(msg)
          visible.value = false
          updateListFunc(1)
        }
      })
    }

    const updateListFunc = (current: number | undefined) => {
      /***
       * 更新列表
       */
      pagination.current = current
      buildingListFunc()
    }
    return {
      dataSource,
      dataColumns,
      pagination,
      loading,
      loadingBtn,
      formState,
      visible,
      title,
      buildingForm,
      option,
      wrapperCol,
      buildingRules,
      buildingFormRef,
      labelCol,
      name,
      onSubmit,
      onSearch,
      onRest,
      onChange,
      onEdit,
      onDel
    }
  }
})
</script>
<style lang="less" scoped>

</style>
